#!/usr/bin/env bash
# ==============================================================================
# What:
# - converts a given CSV file ($inputFile) to plain XML ($outputFile)
# - uses ServingXML for conversion
#
# Note:
#   By default, the resultant XML will look like this:
#
#   <localExport>
#     <record>...</record>
#     <record>...</record>
#     ...
#   </localExport>
#
#   where
#    - the <localExport> is the root element
#    - each row in the CSV is converted to a <record>
#
#   For better self-documentation in the XML, we recommend you change the root
#   element's name to correspond with your local site's abbreviated name.

#   eg. For ACME Inc., we recommend changing the element name to "acmeExport"
#       You can change this in localSXConfig.xml
# 
# ==============================================================================
export SELF=${0##*/}
export BASE_DIR=${BASE_DIR:-"$( cd "$( dirname "$0" )" && pwd )"}
source ${BASE_DIR}/local2rdr.profile

# Configurable parameters
# - uses definitions from iccr2rdr.profile by default
export sxHome=${SERVINGXML_HOME}
export sxConfigFile=${BASE_DIR}/localSXConfig.xml
export inputFile=${CSV2XML_INPUT}
export outputFile=${CSV2XML_OUTPUT}

# Corresponds to /sx:resources/sx:service/@id in localSXConfig.xml
# No change required unless modified in localSXConfig.xml
export sxServiceID=localCSV2XML

# Debug info: prints all internal environment variables on request
if [[ $debug_csv2xml = "true" ]]
then
    echo
    echo "== ${SELF} core variables   =="
    echo "BASE_DIR     : ${BASE_DIR}"
    echo "SCRATCH_DIR  : ${SCRATCH_DIR}"
    echo "AUTH_DIR     : ${AUTH_DIR}"
    echo "TOOLS_DIR    : ${TOOLS_DIR}"
    echo "== ${SELF} script variables =="
    echo "SERVINGXML_HOME: ${SERVINGXML_HOME}"
    echo "sxHome         : ${sxHome}"
    echo "sxConfigFile   : ${sxConfigFile}"
    echo "CSV2XML_INPUT  : ${CSV2XML_INPUT}"
    echo "inputFile      : ${inputFile}"
    echo "CSV2XML_OUTPUT : ${CSV2XML_OUTPUT}"
    echo "outputFile     : ${outputFile}"
    echo
fi


echo
echo "  executing ${SELF} ..."

if [[ -e ${inputFile} ]]
then
   chmod u+x ${sxHome}/servingxml
   ${sxHome}/servingxml -r ${sxConfigFile} -i ${inputFile} -o ${outputFile} ${sxServiceID}

   if [[ $? = 0 ]]
   then
      echo "  finished: completed conversion of"
      echo "    ${inputFile}"
      echo "   to"
      echo "    ${outputFile}"
      echo
      exit 0
   else
      echo "  failure: some error occurred"
      echo
      exit 1
   fi
else 
   echo "  error: missing input file: ${inputFile}"                                                       
   echo
   exit 1
fi
